from django.db.models import Q
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from task.serializers import CmdHistorySerializer
from task.task import SSH
from tools.viewsets import StandardPagination
from rest_framework.viewsets import ReadOnlyModelViewSet
from .models import CommandHistory


class CmdAPIView(APIView):
    def post(self, request):
        params = request.data
        client = SSH(InstanceId=params.get('InstanceId'))
        result = client.do_cmd(params.get('command'))
        return Response({'code': 200, 'msg': '执行成功', 'data': [result]})


class CmdHistoryViewSet(ReadOnlyModelViewSet):
    # 用一个视图集替代MachineList和MachineDetail两个视图
    serializer_class = CmdHistorySerializer
    pagination_class = StandardPagination

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        status = self.request.query_params.get('status')  # success, failed
        objects = CommandHistory.objects
        if keyword:
            # 查询的高阶操作:或者的关系
            objects = objects.filter(
                Q(cmd__contains=keyword) | Q(cmdResult__contains=keyword)
            )
        if status:
            objects = objects.filter(status=status)
        return objects.all()
